package com.twu.biblioteca.transaction;

import com.twu.biblioteca.item.Item;
import com.twu.biblioteca.item.Items;
import com.twu.biblioteca.user.User;
import com.twu.biblioteca.utils.IO;

/**
 * Created by Enrico on 18/09/2014.
 */
public class TransactionManager {

    private Transaction transaction;

    public TransactionManager(Items<? extends Item> items) {
        this.transaction = new Transaction(items);
    }

    public void setup(User user) {
        char choice = validChoice();
        while (!isExit(choice)) {
            menu(choice, user);
            choice = validChoice();
        }
    }

    public char validChoice() {
        char choice = readChoice();
        while (!valid(choice)) {
            explainError();
            choice = readChoice();
        }
        return choice;
    }

    public char readChoice() {
        System.out.print("\nList, Checkout, Return or Exit (l/c/r/x): ");
        return Character.toLowerCase(IO.nextChar());
    }

    public boolean valid(char choice) {
        String choices = "lcrx";
        return choices.contains(Character.toString(choice));
    }

    public void menu(char choice, User user) {
        switch (choice) {
            case 'l':
                transaction.listItems();
                break;
            case 'c':
                doCheckout(user);
                break;
            case 'r':
                doReturn(user);
                break;
        }
    }

    public void doCheckout(User user) {
        transaction.doCheckout(readTitle(), user);
    }

    public void doReturn(User user) {
        transaction.doReturn(readTitle(), user);
    }

    public String readTitle() {
        System.out.print("Select a title: ");
        return IO.nextLine();
    }

    private void explainError() {
        System.out.println("Select a valid option!");
    }

    public boolean isExit(char choice) {
        return choice == 'x';
    }
}


